﻿using System;
using System.Collections.Generic;
using System.Text;

namespace Fetion.Core
{
    public delegate void EventControllerMessageReciev(TcpChannel channel,object e);
    public class ChannelController
    {
        public ChannelController(TcpChannel channel)
        {
            channel.Receive += OnReceive;
        }
        private static Dictionary<Type, MessageHandlerAction> mHandlers = new Dictionary<Type, MessageHandlerAction>(32);
        /// <summary>
        /// 消息接收委托
        /// </summary>
        public event EventControllerMessageReciev Receive;

        private void OnReceive(object sender, EventChannelReceiveArgs e)
        {

            object msg = e.Message;
            if (mHandlers.Count == 0)
            {
                if (Receive != null)
                    Receive(e.Channel,msg);
            }
            else
            {
                
                Type key = msg.GetType();

                MessageHandlerAction action = null;
                if(mHandlers.ContainsKey(msg.GetType()))
                    action = mHandlers[msg.GetType()];
                if (action != null)
                {
                    action.Execute(e.Channel, msg);

                }
                else
                {
                    if (Receive != null)
                        Receive(e.Channel, msg);
                }
            }
        }
        /// <summary>
        /// 注册信息处理器
        /// </summary>
        /// <param name="handler">IMessageHandler</param>
        public static void RegisterHandler(IMessageHandler handler)
        {
            if (handler != null)
            {
                lock (mHandlers)
                {
                    IList<MessageHandlerAction> actions = MessageHandlerAction.GetActions(handler);
                    if (actions.Count > 0)
                    {
                        for (int i = 0; i < actions.Count; i++)
                        {
                            MessageHandlerAction item=actions[i];
                            if (!mHandlers.ContainsKey(item.Type))
                                mHandlers.Add(item.Type, item);
                            else
                                mHandlers[item.Type] = item;
                        }
                      
                    }
                }
            }
        }
    }
}
